package api.pay;

import bean.Goods;
import db.GoodsMockTable;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PayServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session=request.getSession();
        response.setContentType("text/html;charset=utf-8");
        if(session.getAttribute("user")==null){//如果session新创建的，则表示这个用户还没有登录，是刚开始访问的
            String msg="您还没有登录呢！三秒后自动跳转到登录页面！";
            response.getWriter().write(msg);
            response.setHeader("Refresh","3;URL=/login.html");
        }else{
//            Goods goods5= GoodsMockTable.getUserByName("苹果手机5");
//            Goods goods3= GoodsMockTable.getUserByName("苹果手机3");
//            List<Goods> goodses=new ArrayList<Goods>();
//            goodses.add(goods3);
//            goodses.add(goods5);
//            session.setAttribute("cart",goodses);

            List<Goods> goodses=(List<Goods>)session.getAttribute("cart");
            int len=0;
            double total=0;
            if(goodses!=null) len=goodses.size();
            for (int i = 0; i < len; i++) {
                total=total+goodses.get(i).getPrice()*1;
            }
            Cookie cookie=new Cookie("JSESSIONID",session.getId());
            response.addCookie(cookie);
            response.getWriter().write("支付成功，总价为："+total+"<br/>");
            response.getWriter().write("<a href='/logout'>退出登录</a>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
